package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.model.RoleGroup;
import com.pactera.jep.sys.model.StaffGroup;
import com.pactera.jep.sys.model.StaffGroupRoleGroupMap;
import com.pactera.jep.sys.service.StaffGroupRoleGroupMapService;
import com.pactera.jep.sys.service.StaffGroupService;
import com.pactera.jep.web.code.WebCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="用户组关联角色组")
@RestController
@RequestMapping("/staffGroupRoleGroupMap")
public class StaffGroupRoleGroupMapRestController extends BaseRestController<StaffGroupRoleGroupMap> {
	Logger logger = LoggerFactory.getLogger(StaffGroupRoleGroupMapRestController.class);

	@Autowired
	private StaffGroupRoleGroupMapService	mapService;
	
	@Autowired
	private StaffGroupService				staffGroupService;

	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(String token, Page<StaffGroupRoleGroupMap> page, List<Filter> filters, List<Order> orders,HttpServletRequest request) {
		
		mapService.query(page, filters, orders);
	}

	/**
	 * 用户组关联角色组保存
	 * @param jsonData
	 * @return
	 */
	@ApiOperation(value = "用户组关联角色组保存")
	@PostMapping(value = "/saveRoleGroup")
	public Map<String, Object> saveRoleGroup(@RequestBody JSONObject jsonData) {
		//String staffGroupCode, String jsonRoleGroupList
		Map<String, Object> tips = new HashMap<String, Object>();
		
		try 
		{

			String staffGroupCode = jsonData.getString("staffGroupCode");
			String jsonRoleGroupList = jsonData.getString("jsonRoleGroupList");
			/*重新添加新设定的角色*/
			StaffGroup staffGroup = staffGroupService.get(staffGroupCode);
			List<RoleGroup> list = JSON.parseArray(jsonRoleGroupList, RoleGroup.class);
			mapService.saveRoleGroup(staffGroup, list);
			
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}
	
}